//use package we.go demo, http://webgo.io/
package main

import (
    "github.com/hoisie/web"
    "io"
    "bytes"
    "strconv"
    "fmt"
)

//main entry
//
//web.go URL Handling 
//support regular expression
//web.Get, web.Post, web.Put, web.Delete, web.Match
func main() {
    web.Get("/", mainPage)
    web.Get("/hello/(.*)", hello)
    web.Run("0.0.0.0:9999")
    //go localhost:9999
}

//mainPage route handler, test buff output
//
//The fields in 'ctx *web.Context' are
//1.ctx.Request, type: http.Request
//2.ctx.Params, type: map[string]string, the flattened version of ctx.Request.Form
//3.ctx.ResponseWriter, type: http.ResponseWriter
//4.ctx.Server, type: web.Server
//
//ctx *web.Context methods
//ctx.NotFound(msg) 404
//ctx.Abort(status,msg) 4xx,5xx
//ctx.Redirect(status,url) 3xx
//
//Set response headers
//ctx.SetHeader("X-Name", "value", true)
//
//Setting cookies
//ctx.SetCookie(web.NewCookie("value", val))
//
//A handler function is required to have the same number of arguments
//as regular expression groups in its url pattern.
func mainPage(ctx *web.Context) {
    var buf bytes.Buffer
    buf.WriteString("<h2>Home</h2>")
    buf.WriteString("<p><a href='/hello/world'>Hello</a><p>")
    buf.WriteString("<p><a href='/hello/?a=4&b=5'>Compute 4+5</a><p>")
    buf.WriteString("<p><a href='/about.html'>About</a><p>")
    //copy the buffer to the response
    io.Copy(ctx, &buf)
}

//hello route handler, test web output and getting parameters
//
//go http://localhost:9999/hello/world
//go http://localhost:9999/hello/?a=3&b=4
func hello(ctx *web.Context, val string) string {
    sum := 0
    for k,v := range ctx.Params {
        if i, err := strconv.Atoi(v); err == nil {
            sum += i
        }
        println(k, v)
    }
    if len(ctx.Params) != 0{
        fmt.Printf("%v",len(ctx.Params))
        ctx.WriteString("Sum: " + strconv.Itoa(sum))
    }    
    return "<h2>hello " + val + "</h2>"
}

//package html/template output HTML